// pages/record/record.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const $ = db.command.aggregate

Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      dishName: '',
      duration: 30,
      ingredients: [],
      difficulty: 3,
      images: []
    },
    ingredientInput: '',
    searchResults: [],
    errors: {},
    submitting: false,
    showRecordForm: false,
    foodList: [],
    pageSize: 10,
    lastId: null,
    loading: false,
    refreshing: false,
    noMore: false,
    currentLocation: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getLocation()
    this.loadFoodList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 烹饪时长变化
  onDurationChange(e) {
    this.setData({
      'formData.duration': Number(e.detail) || 0
    })
  },

  // 搜索食材
  async onSearchIngredient(e) {
    const keyword = e.detail
    if (keyword.length < 2) {
      this.setData({ searchResults: [] })
      return
    }

    try {
      const { result } = await wx.cloud.callFunction({
        name: 'searchIngredients',
        data: { keyword }
      })

      this.setData({
        searchResults: result.data || []
      })
    } catch (err) {
      console.error('搜索食材失败', err)
    }
  },

  // 选择食材
  selectIngredient(e) {
    const { ingredient } = e.currentTarget.dataset
    const ingredients = [...this.data.formData.ingredients]
    
    if (!ingredients.find(item => item.name === ingredient.name)) {
      ingredients.push(ingredient)
      this.setData({
        'formData.ingredients': ingredients,
        ingredientInput: '',
        searchResults: []
      })
    }
  },

  // 移除食材
  removeIngredient(e) {
    const { index } = e.currentTarget.dataset
    const ingredients = [...this.data.formData.ingredients]
    ingredients.splice(index, 1)
    this.setData({
      'formData.ingredients': ingredients
    })
  },

  // 难度评分变化
  onRateChange(e) {
    this.setData({
      'formData.difficulty': e.detail
    })
  },

  // 上传图片
  async afterRead(e) {
    const { file } = e.detail
    const tasks = file.map(f => this.uploadFile(f))
    
    try {
      const uploadResults = await Promise.all(tasks)
      const images = [...this.data.formData.images, ...uploadResults]
      this.setData({
        'formData.images': images
      })
    } catch (err) {
      console.error('上传图片失败', err)
      wx.showToast({
        title: '上传图片失败',
        icon: 'error'
      })
    }
  },

  // 上传单个文件
  async uploadFile(file) {
    const cloudPath = `cooking/${Date.now()}-${Math.random().toString(36).slice(-6)}.${file.url.split('.').pop()}`
    
    const { fileID } = await wx.cloud.uploadFile({
      cloudPath,
      filePath: file.url
    })

    return {
      url: file.url,
      fileID
    }
  },

  // 删除图片
  onDeleteImage(e) {
    const { index } = e.detail
    const images = [...this.data.formData.images]
    const deletedImage = images.splice(index, 1)[0]

    // 删除云存储文件
    wx.cloud.deleteFile({
      fileList: [deletedImage.fileID]
    })

    this.setData({
      'formData.images': images
    })
  },

  // 表单验证
  validateForm() {
    const errors = {}
    const { dishName, duration } = this.data.formData

    if (!dishName.trim()) {
      errors.dishName = '请输入菜品名称'
    }

    if (!duration || duration < 1) {
      errors.duration = '请输入有效的烹饪时长'
    }

    this.setData({ errors })
    return Object.keys(errors).length === 0
  },

  // 提交表单
  async onSubmit() {
    if (!this.validateForm()) return

    this.setData({ submitting: true })

    try {
      const { formData } = this.data

      await db.collection('cooking').add({
        data: {
          ...formData,
          openid: app.globalData.openid,
          createTime: db.serverDate()
        }
      })

      wx.showToast({
        title: '发布成功',
        icon: 'success'
      })

      // 返回上一页或跳转到列表页
      wx.navigateBack()

    } catch (err) {
      console.error('提交失败', err)
      wx.showToast({
        title: '发布失败',
        icon: 'error'
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 显示记录弹窗
  showRecordPopup() {
    wx.navigateTo({
      url: '/pages/add-cooking/add-cooking'
    })
  },

  // 加载美食列表
  async loadFoodList(refresh = false) {
    if (this.data.loading || (!refresh && this.data.noMore)) return

    this.setData({ loading: true })

    try {
      const { currentLocation, lastId, pageSize } = this.data
      let query = db.collection('food')
        .orderBy('createTime', 'desc')
        .limit(pageSize)

      if (!refresh && lastId) {
        query = query.where({
          _id: _.gt(lastId)
        })
      }

      const { data } = await query.get()

      // 计算距离
      if (currentLocation && currentLocation.latitude) {
        data.forEach(item => {
          if (item.location) {
            item.distance = this.calculateDistance(
              currentLocation,
              item.location
            )
          }
        })
      }

      this.setData({
        foodList: refresh ? data : [...this.data.foodList, ...data],
        lastId: data.length ? data[data.length - 1]._id : null,
        noMore: data.length < pageSize,
        loading: false,
        refreshing: false
      })
    } catch (err) {
      console.error('加载数据失败', err)
      this.setData({
        loading: false,
        refreshing: false
      })
    }
  },

  // 下拉刷新
  onRefresh() {
    this.setData({
      refreshing: true,
      noMore: false,
      lastId: null
    })
    this.loadFoodList(true)
  },

  // 上拉加载更多
  onLoadMore() {
    this.loadFoodList()
  },

  // 获取当前位置
  async getLocation() {
    try {
      const { latitude, longitude } = await wx.getLocation({
        type: 'gcj02'
      })
      this.setData({
        currentLocation: {
          latitude,
          longitude
        }
      })
    } catch (err) {
      console.error('获取位置失败', err)
      // 即使获取位置失败，也继续加载列表
      this.loadFoodList()
    }
  },

  // 计算两点之间的距离（米）
  calculateDistance(point1, point2) {
    const R = 6371000 // 地球半径（米）
    const lat1 = this.toRadians(point1.latitude)
    const lat2 = this.toRadians(point2.latitude)
    const deltaLat = this.toRadians(point2.latitude - point1.latitude)
    const deltaLon = this.toRadians(point2.longitude - point1.longitude)

    const a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +
              Math.cos(lat1) * Math.cos(lat2) *
              Math.sin(deltaLon/2) * Math.sin(deltaLon/2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))

    return Math.round(R * c)
  },

  toRadians(degrees) {
    return degrees * Math.PI / 180
  }
})